package org.dubnation.base.excel.upload.util;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import org.apache.poi.ss.formula.functions.T;
import org.dubnation.base.excel.upload.dto.EmployeeDTO;
import org.dubnation.org.domain.Department;
import org.dubnation.org.domain.Employee;
import org.dubnation.org.mapper.DepartmentMapper;
import org.dubnation.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 自定义校验逻辑
 */
@Component
public class ExcelVerifyHandler implements IExcelVerifyHandler<EmployeeDTO> {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Autowired(required = false)
    private DepartmentMapper departmentMapper;

    @Override
    public ExcelVerifyHandlerResult verifyHandler(EmployeeDTO employeeDTO) {
        //1.核验导入的数据是否在数据库已存在, 若已存在则不能导入
        if (Objects.nonNull((employeeMapper.queryByName(employeeDTO.getUsername()))))
            return new ExcelVerifyHandlerResult(false, "该条数据已存在");
        //2.检验性别只有男女
        Integer sex = Integer.valueOf(employeeDTO.getSex());
        if (!(sex.equals(1) || sex.equals(0)))
            return new ExcelVerifyHandlerResult(false, "性别只能是男和女");
        //3.检验状态是否只有正常、锁定、注销
        Integer state = Integer.valueOf(employeeDTO.getState());
        if (!(state.equals(Employee.AVAILABLE) || state.equals(Employee.UNAVAILABLE) || state.equals(Employee.LOGOUT)))
           return new ExcelVerifyHandlerResult(false, "员工状态只有正常、锁定、注销");
        //4.检验部门是否在数据库中已存在, 若不存在则不能导入
        if (Objects.isNull(departmentMapper.queryByName(employeeDTO.getDepartmentDTO().getName()))){
            return new ExcelVerifyHandlerResult(false, "员工所属的部门不存在");
        }
        return new ExcelVerifyHandlerResult(true);
    }
}